package server.console.groups.cashshop;

import com.alee.extended.painter.TitledBorderPainter;
import com.alee.extended.panel.GroupPanel;
import com.alee.laf.button.WebButton;
import com.alee.laf.combobox.WebComboBox;
import com.alee.laf.label.WebLabel;
import com.alee.laf.panel.WebPanel;
import com.alee.laf.rootpane.WebFrame;
import com.alee.laf.scroll.WebScrollPane;
import com.alee.laf.text.WebTextArea;
import com.alee.laf.text.WebTextField;
import database.DatabaseConnection;
import server.console.Start;
import tools.StringUtil;

import javax.swing.*;
import java.awt.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Random;

public class CashCodeGeneratePane extends WebFrame {

    private static final WebTextField 面值 = new WebTextField(8), 数量 = new WebTextField(4);
    private static final WebTextArea cdkeys = new WebTextArea();
    private static final Object initLock = new Object();
    private static CashCodeGeneratePane instance = null;
    private static Random randGen = null;
    private static char[] numbersAndLetters = null;
    private static int selectType = 0;

    CashCodeGeneratePane() {
        super("CDKEY生成");
        setIconImage(Start.getMainIcon().getImage());
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);

        add(new WebPanel(new BorderLayout(5, 5)) {
            {
                setPreferredSize(400, 500);
                setResizable(false);
                setMargin(2, 5, 2, 5);
                add(new WebPanel() {
                    {
                        //region 填写面值和数量的控件
                        setMargin(5);
                        add(new GroupPanel(5,
                                        new WebComboBox(new String[]{"余额", "点券", "抵用券"}) {
                                            {
                                                addItemListener(e -> {
                                                    selectType = ((WebComboBox) e.getSource()).getSelectedIndex();
                                                });
                                                setSelectedIndex(0);
                                            }
                                        },
                                        new GroupPanel(new WebLabel("面值: "), 面值),
                                        new GroupPanel(new WebLabel("数量: "), 数量),
                                        new WebButton("生成CDKEY") {
                                            {
                                                addActionListener(e -> {
                                                    if (面值.getText().isEmpty() || 数量.getText().isEmpty()) {
                                                        JOptionPane.showMessageDialog(instance, "面值与余额不能为空");
                                                        return;
                                                    }
                                                    if (!StringUtil.isNumber(面值.getText()) || !StringUtil.isNumber(数量.getText())) {
                                                        JOptionPane.showMessageDialog(instance, "面值与余额只能填入数字");
                                                        return;
                                                    }
                                                    int value = Integer.parseInt(数量.getText());
                                                    StringBuilder text = new StringBuilder();
                                                    for (Integer i = 0; i < value; i++) {
                                                        String key = randomString(20);
                                                        if (!makeCDKey(key, selectType, Integer.parseInt(面值.getText()))) {
                                                            i--;
                                                        }
                                                        text.append(key).append("\r\n");
                                                    }
                                                    cdkeys.clear();
                                                    cdkeys.setText(text.toString());
                                                });
                                            }
                                        }
                                )
                        );
                        //endregion
                    }
                }, BorderLayout.NORTH);
                add(new WebPanel() {
                    {
                        setPainter(new TitledBorderPainter("生成的CDKEY列表"));
                        add(new WebScrollPane(cdkeys));
                    }
                });
            }
        });
    }

    public static CashCodeGeneratePane getInstance() {
        if (instance == null) {
            instance = new CashCodeGeneratePane();
        }
        return instance;
    }

    public static boolean makeCDKey(String code, int type, int count) {
        try (Connection con = DatabaseConnection.getConnection()) {
            try (PreparedStatement ps = con.prepareStatement("INSERT INTO nxcode(`code`, `type`, `count`) VALUES (?, ?, ?)")) {
                ps.setString(1, code);
                ps.setInt(2, type);
                ps.setInt(3, count);
                ps.executeUpdate();
            }
            return true;
        } catch (SQLException e1) {
            e1.printStackTrace();
            return false;
        }
    }

    //得到一个随机长度的字符串，只有数字和字符
    public static String randomString(int length) {
        if (length < 1) {
            return null;
        }
        if (randGen == null) {
            synchronized (initLock) {
                if (randGen == null) {
                    randGen = new Random();
                    numbersAndLetters = ("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ").toCharArray();
                }
            }
        }
        char[] randBuffer = new char[length];
        for (int i = 0; i < randBuffer.length; i++) {
            randBuffer[i] = numbersAndLetters[randGen.nextInt(35)];
        }
        return new String(randBuffer);
    }

}
